<?php
class Login_model extends CI_Model {
	public function __construct() {
		parent::__construct();
	}

	// $loginData contains
	// username and password to be verified
	public function verify($loginData = FALSE) {
		if (!$loginData) {
			return FALSE;
		}
		$query = $this->db
		              ->select('name, pepper, passhash')
		              ->from('users')
		              ->where('username', $loginData['username'])
		              ->limit(1)
		              ->get()
		              ->row_array();
		if (count($query) < 1) {
			return FALSE;
		}
		if ($query['passhash'] != hash('sha256', $query['pepper'] . $loginData['password'])) {
			return FALSE;
		}
		return $query['name'];
	}

	public function verify_remember_cookie($value = FALSE) {
		if (!$value) {
			return FALSE;
		}
		if (!$value['sign'] == md5($value['timestamp'] . $value['seed'])) {
			return FALSE;
		}
		$query = $this->db
		              ->select('username, name')
		              ->from('users')
		              ->where('username', $value['username'])
		              ->limit(1)
		              ->get()
		              ->row_array();
		if (count($query) < 1) {
			return FALSE;
		}
		return $query;
	}

	public function remember_cookie() {
		$value['username'] = $this->session->userdata('username');
		$value['timestamp'] = time();
		$value['seed'] = bin2hex(openssl_random_pseudo_bytes(16));
		$value['sign'] = md5($value['timestamp'] . $value['seed']);
		return $value;
	}
}